import { SetupContext, computed, defineComponent, inject, onMounted, ref } from 'vue';
import { DynamicFormGroupPropsType, dynamicFormGroupProps } from '../component/dynamic-form-group/dynamic-form-group.props';
import { DesignerItemContext } from '../../../designer-canvas/src/types';
import { useDesignerComponent } from '../../../designer-canvas/src/composition/function/use-designer-component';
import { useDesignerRules } from './use-designer-rules';

export default defineComponent({
    name: 'FResponseFormDesign',
    props: dynamicFormGroupProps,
    emits: [],
    setup(props: DynamicFormGroupPropsType, context: SetupContext) {
        const elementRef = ref();
        const designItemContext = inject<DesignerItemContext>('design-item-context') as DesignerItemContext;
        const designerRulesComposition = useDesignerRules(designItemContext.schema, designItemContext.parent?.schema);
        const componentInstance = useDesignerComponent(elementRef, designItemContext, designerRulesComposition);

        onMounted(() => {
            elementRef.value.componentInstance = componentInstance;
        });

        context.expose(componentInstance.value);

        const responseFormClass = computed(() => {
            const customClassArray = props.customClass.split(' ');
            const classObject = {
                'drag-container': true
            } as Record<string, boolean>;
            customClassArray.reduce((result: Record<string, boolean>, classString: string) => {
                result[classString] = true;
                return result;
            }, classObject);
            return classObject;
        });

        return () => {
            return (
                <div
                    ref={elementRef}
                    class={responseFormClass.value}
                    data-dragref={`${designItemContext.schema.id}-container`}
                    data-associate={`${designItemContext.schema.id}-component`}>
                    {context.slots.default && context.slots.default()}
                </div>
            );
        };
    }
});
